摘要:
19 正则表达式匹配
面试题19 正则表达式匹配
题目:
请实现一个函数用来匹配包含’. ‘和’‘的正则表达式。模式中的字符’.’表示任意一个字符,而’‘表示它前面的字符可以出现任意次(含0次)。在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串”aaa”与模式”a.a”和”abaca”匹配,但与”aa.a”和”ab*a”均不匹配。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Solution { public boolean isMatch(String A, String B) { int a=A.length(); int b=B.length(); boolean[][] f=new boolean[a+1][b+1]; for(int i=0;i<=a;i++){ for(int j=0;j<=b;j++){ if(j==0){ f[i][j]=i==0; }else{ if(B.charAt(j-1)!='*'){ if(i>0&&(A.charAt(i-1)==B.charAt(j-1)||B.charAt(j-1)=='.')) f[i][j]=f[i-1][j-1]; }else{ if(j>=2){ f[i][j] |=f[i][j-2]; } if(i>=1&&j>=2&&(A.charAt(i-1)==B.charAt(j-2)||B.charAt(j-2)=='.')) f[i][j] |=f[i-1][j]; } } } } return f[a][b]; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution: def isMatch(self, s: str, p: str) -> bool: s, p = '#'+s, '#'+p m, n = len(s), len(p) dp = [[False]*n for _ in range(m)] dp[0][0] = True for i in range(m): for j in range(1, n): if i == 0: dp[i][j] = j > 1 and p[j] == '*' and dp[i][j-2] elif p[j] in [s[i], '.']: dp[i][j] = dp[i-1][j-1] elif p[j] == '*': dp[i][j] = j > 1 and dp[i][j-2] or p[j-1] in [s[i], '.'] and dp[i-1][j] else: dp[i][j] = False return dp[-1][-1]
|